﻿
using HW.Application.Share.Prism;
using HW.Logger;
using Prism.Ioc;
using Prism.Modularity;
using Prism.Unity;
using Shell.Views;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace Shell
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : PrismApplication
    {
        private Mutex _mutex;

        //异常处理
        public App()
        {

            //程序域异常
            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                Logs.LogError((Exception)(e.ExceptionObject));
            };

            //应用程序异常
            Current.DispatcherUnhandledException += (s, e) =>
            {
                Logs.LogError(e.Exception);
            };

            //多线程异常
            TaskScheduler.UnobservedTaskException += (s, e) =>
            {
                Logs.LogError(e.Exception);
            };
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            const string mutexName = "WpfSingleInstanceMutex";
            bool createdNew;

            // 尝试创建命名互斥体
            _mutex = new Mutex(true, mutexName, out createdNew);

            if (!createdNew)
            {
                // 如果已经有同名的互斥体存在，则说明程序已经在运行中
                MessageBox.Show("程序已经在运行中，禁止重复启动。");
                Current.Shutdown();
                return;
            }

            base.OnStartup(e);

            Logs.LogInfo("启动应用程序");
        }

        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);

            Logs.LogInfo("关闭应用程序");
        }


        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {

        }

        protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)

        {
            base.ConfigureModuleCatalog(moduleCatalog);
            moduleCatalog.AddModule<HW.Core.CoreModule>();
            // 把新的模块引入到主程序的模块集合中，统一管理
            // 如果考虑不引用Module程序集的话，可使用自动扫描/配置文件XML
        }

        protected override IModuleCatalog CreateModuleCatalog()
        {
            return new DirectoryModuleCatalog() { ModulePath = ModuleNames.ModulePath }; //配置模块路径 需配置Module模块的项目生成事件
        }
    }
}
